package com.example.bt_arduino;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    Button mDiscovery, mSend;
    ListView mPairedList;
    EditText mWriteMsg;
    TextView mStatus, msg_box;
    BluetoothAdapter mBluetoothAdapter;
    BluetoothDevice[] mmdevice;

    SendReceive sendMsg;

//    ArrayList<String> mbondeddevicelist = new ArrayList<String>();
//    List<BluetoothDevice> mBondeddevicedlist = new ArrayList<>();
//    ArrayAdapter<String> mbonneddeviceAdapter;

    static final int STATE_CONNECTING = 1;
    static final int STATE_CONNECTED = 2;
    static final int STATE_CONNECTION_FAILED = 3;
    static final int STATE_MESSAGE_RECEIVED = 4;

    private static final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static final int ACTION_REQUEST_BT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDiscovery = findViewById(R.id.discovery);
        mSend = findViewById(R.id.send);
        mPairedList = findViewById(R.id.pairedlist);
        mStatus = findViewById(R.id.status);
        msg_box = findViewById(R.id.msg_box);
        mWriteMsg = findViewById(R.id.write_msg);


        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, ACTION_REQUEST_BT);
        }

//        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//        registerReceiver(receiver, filter);
//        mbonneddeviceAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, mbondeddevicelist);
//        mPairedList.setAdapter(mbonneddeviceAdapter);

        showBondedDevice();

        mPairedList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Connect connect = new Connect(mmdevice[i]);
                connect.start();

                mStatus.setText("Connecting");
            }
        });

        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = String.valueOf(mWriteMsg.getText());
                sendMsg.write(string.getBytes());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ACTION_REQUEST_BT)
        {
            if (resultCode == RESULT_OK )
            {
                Toast.makeText(getApplicationContext(), "Bluetooth is Enable!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Bluetooth Enabling Cancelled", Toast.LENGTH_SHORT).show();
            }
        }
    }


//    private BroadcastReceiver receiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//
//            String action = intent.getAction();
//            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                //显示设备已经配对
//                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
//                    mbondeddevicelist.add(device.getName() + "\n" + device.getAddress());
//                    mBondeddevicedlist.add(device);
//                    mbonneddeviceAdapter.notifyDataSetChanged();
//
//                } else if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//
//                    mdevicelist.add(device.getName() + "\n" + device.getAddress());
//                    mmDevicelist.add(device);
//                    mdeviceAdapter.notifyDataSetChanged();
//
//                }
//            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//                Toast.makeText(getApplicationContext(), "The Diacovery IS Finished", Toast.LENGTH_SHORT).show();
//            }
//        }
//    };

    public void showBondedDevice()
    {
        mDiscovery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                String[] string = new String[pairedDevices.size()];
                mmdevice = new BluetoothDevice[pairedDevices.size()];
                int index = 0;

                if (pairedDevices.size() >0)
                {
                    for (BluetoothDevice device : pairedDevices)
                    {
                        mmdevice[index] = device;
                        string[index] = device.getName() + "\n" +device.getAddress();
                        index ++;
                    }

                    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, string);
                    mPairedList.setAdapter(arrayAdapter);
                }
            }
        });
    }

//    public void onDestroy() {
//
//        super.onDestroy();
//        //解除注册
//        unregisterReceiver(receiver);
//    }

        Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case STATE_CONNECTING:
                    mStatus.setText("Connecting");
                    break;
                case STATE_CONNECTED:
                    mStatus.setText("Connected");
                    break;
                case STATE_CONNECTION_FAILED:
                    mStatus.setText("Connection Failed");
                    break;
                case STATE_MESSAGE_RECEIVED:
                    byte[] readBuffer = (byte[]) msg.obj;
                    String tempMsg = new String(readBuffer, 0, msg.arg1);
                    msg_box.setText(tempMsg);
                    break;
            }
            return true;
        }

    });

    private class Connect extends Thread {
        private final BluetoothDevice mdevice;
        private BluetoothSocket socket = null;


        private Connect(BluetoothDevice device) {
            this.mdevice = device;

            try {
                socket = device.createRfcommSocketToServiceRecord(mUUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            mBluetoothAdapter.cancelDiscovery();
            try {
                socket.connect();
                Message message = Message.obtain();
                message.what = STATE_CONNECTED;
                handler.sendMessage(message);

                sendMsg = new SendReceive(socket);
                sendMsg.start();

            } catch (IOException e) {
                e.printStackTrace();
                handler.sendMessage(handler.obtainMessage(STATE_CONNECTION_FAILED));
            }

        }
    }

    private class SendReceive extends Thread
    {
        private final BluetoothSocket bluetoothSocket;
        private final InputStream inputStream ;
        private final OutputStream outputStream ;

        private SendReceive(BluetoothSocket socket) {
            bluetoothSocket = socket;
            InputStream tempIn = null;
            OutputStream tempOut = null;
            // 使用临时对象获取输入和输出流，因为成员流是最终的
            try {
                tempIn = bluetoothSocket.getInputStream();
                tempOut = bluetoothSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            inputStream = tempIn;
            outputStream = tempOut;
        }

        public void run()
        {
            byte[] buffer = new byte[1024];
            // 从read()返回bytes
            int bytes;

            while (true) {
                try {

                    bytes = inputStream.read(buffer);
                    // 从InputStream读取数据
                    if (bytes > 0) {

//                      Message message = handler.obtainMessage(STATE_MESSAGE_RECEIVED, new String(buffer, 0, bytes, "utf-8"));
//                      handler.sendMessage(message);
                        handler.obtainMessage(STATE_MESSAGE_RECEIVED, bytes, -1, buffer).sendToTarget();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void write(byte[] bytes)
        {
            try {
                outputStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}



